package com.blb.community.handler;

import com.blb.community.entity.vo.UserVO;
import com.blb.community.utils.JwtUtil;
import com.blb.community.utils.ResponseResult;
import com.blb.community.utils.RsaUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author 帅帅
 * @Date 2022/6/28 10:56
 * @PackageName:com.blb._20220625springboot.handler
 * @ClassName: LoginSuccessHandler
 * @Description: TODO
 * @Version 1.0
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {


    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        User user = (User) authentication.getPrincipal();
        String token = JwtUtil.generateToken(user.getUsername(), RsaUtil.privateKey, JwtUtil.EXPIRE_MINUTES);
        UserVO userVo = new UserVO(user.getUsername(), token);
        ResponseResult.write(httpServletResponse, ResponseResult.ok(userVo));
    }
}
